package com.zhl.utils;

import java.sql.SQLException;

/**
 * 事务管理的工具类
 *
 * 自定义的事务管理器
 */
public class TransactionManager {
    //注入ConnectionUtils
    private ConnectionUtils connectionUtils;

    public void setConnectionUtils(ConnectionUtils connectionUtils) {
        this.connectionUtils = connectionUtils;
    }

    /**
     * 事务开启
     */
    public void  benginTransaction(){
        try {
            connectionUtils.getConnection().setAutoCommit(false);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 提交事务
     */
    public void  commit(){
        try {
            connectionUtils.getConnection().commit();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 事务回滚
     */
    public void  rollback(){
        try {
            connectionUtils.getConnection().rollback();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 释放连接
     * 连接对象为空--从数据源存入本地线程中
     */
    public void  close(){
        connectionUtils.remove();
    }

}
